package com.hengxinguotong.zhihuichengjian.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Administrator on 2017/8/31.
 */

public class MyDatabaseHelper extends SQLiteOpenHelper
{

    private static final String DATABASE_NAME = "ZHCJ.db";
    private static final int NEW_VERSION = 2;
    public static final String t_download = "download_info";//断点下载表
    public static final String t_news = "news";//新闻表
    private static volatile SQLiteDatabase mSQLiteDatabase = null;

    public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        String createNewsSql = "create table " + t_news +
                "(id varchar primary key," +
                "title text," +
                "content text," +
                "link varchar," +
                "path varchar);";
        db.execSQL(createNewsSql);
        onUpgrade(db, 1, NEW_VERSION);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        for (int i = oldVersion; i < newVersion; i++)
        {
            switch (i)
            {
                case 1:
                    upgrade1To2(db);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                default:
                    break;
            }
        }
    }

    private void upgrade1To2(SQLiteDatabase db)
    {
        String createDownload = "CREATE TABLE IF NOT EXISTS " + t_download +
                "(_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "thread_id INTEGER," +
                "start_pos INTEGER," +
                "end_pos INTEGER," +
                "compelete_size INTEGER," +
                "url VARCHAR(1000));";
        db.execSQL(createDownload);
    }

    public static SQLiteDatabase getInstance(Context context)
    {
        if (mSQLiteDatabase == null)
        {
            synchronized (MyDatabaseHelper.class)
            {
                if (mSQLiteDatabase == null)
                {
                    MyDatabaseHelper helper = new MyDatabaseHelper(context, DATABASE_NAME, null, NEW_VERSION);
                    mSQLiteDatabase = helper.getWritableDatabase();
                }
            }
        }
        return mSQLiteDatabase;
    }

    public static void closeDB()
    {
        if (mSQLiteDatabase != null)
        {
            mSQLiteDatabase.close();
        }
    }
}
